using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace DownloadDocumentsBL
{
    public class ZipDocuments
    {
        private SPDocumentLibrary _docLib = null;

        public ZipDocuments(SPDocumentLibrary DocumentLibrary)
        {
            _docLib = DocumentLibrary;
        }


        public SPDocumentLibrary DocumentLibrary
        {
            get { return _docLib; }
            set { _docLib = value; }
        }    

        public void CreateZip(Stream stream)
        {
            SPListItemCollection docs = null;
            List<SPFile> files = new List<SPFile>();

            if (_docLib != null && _docLib.ItemCount > 0)
            {
                docs = _docLib.Items;
                using(ZipOutputStream s = new ZipOutputStream(stream))
                {

                    s.SetLevel(9); // 0 - store only to 9 - means best compression

                    //byte[] buffer = new byte[4096];

                    foreach (SPListItem item in docs)
                    {
                        SPFile file = item.File;       

                        // Using GetFileName makes the result compatible with XP
                        // as the resulting path is not absolute.
                        
                        ZipEntry entry = new ZipEntry(file.Name);

                        // Setup the entry data as required.

                        // Crc and size are handled by the library for seakable streams
                        // so no need to do them here.

                        // Could also use the last write time or similar for the file.
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);

                        
                        CopyStream(file.OpenBinaryStream(), s);
                    }
                }
            }
        }
        //  --------------------------- CopyStream ---------------------------
        /// <summary>
        ///   Copies data from a source stream to a target stream.</summary>
        /// <param name="source">
        ///   The source stream to copy from.</param>
        /// <param name="target">
        ///   The destination stream to copy to.</param>
        private static void CopyStream(Stream source, Stream target)
        {
            const int bufSize = 0x1000;
            byte[] buf = new byte[bufSize];
            int bytesRead = 0;
            while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
                target.Write(buf, 0, bytesRead);
        }// end:CopyStream()

    }
}
